package com.simplehire.service;

import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.text.PDFTextStripper;
import org.apache.poi.xwpf.extractor.XWPFWordExtractor;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;

@Service
public class ResumeParserService {
    
    public String parseResume(MultipartFile file) throws IOException {
        String fileName = file.getOriginalFilename();
        String fileExtension = fileName != null ? 
            fileName.substring(fileName.lastIndexOf(".") + 1).toLowerCase() : "";
        
        try (InputStream inputStream = file.getInputStream()) {
            switch (fileExtension) {
                case "pdf":
                    return parsePdf(inputStream);
                case "docx":
                    return parseDocx(inputStream);
                case "txt":
                    return new String(inputStream.readAllBytes());
                default:
                    throw new IllegalArgumentException("不支持的文件格式: " + fileExtension);
            }
        }
    }
    
    private String parsePdf(InputStream inputStream) throws IOException {
        try (PDDocument document = PDDocument.load(inputStream)) {
            PDFTextStripper stripper = new PDFTextStripper();
            return stripper.getText(document);
        }
    }
    
    private String parseDocx(InputStream inputStream) throws IOException {
        try (XWPFDocument document = new XWPFDocument(inputStream)) {
            XWPFWordExtractor extractor = new XWPFWordExtractor(document);
            return extractor.getText();
        }
    }
}